package handerls

import (
	"github.com/gin-gonic/gin"
	"live-stream-pro/modlers"
	"live-stream-pro/pkg"
	"strconv"
)

func Register(c *gin.Context) {
	username := c.PostForm("username")
	email := c.PostForm("email")
	password := c.PostForm("password")

	user := modlers.User{
		Username: username,
		Email:    email,
		Password: pkg.Md5(password),
	}
	err := modlers.DB.Create(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "注册失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
	return
}

func Login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")

	var user modlers.User
	err := modlers.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return
}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	user_id, _ := strconv.Atoi(c.PostForm("user_id"))

	video := modlers.Video{
		Title:     title,
		Content:   content,
		Img:       img,
		UserID:    user_id,
		LikeCount: 0,
	}

	err := modlers.DB.Create(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {

	var video []modlers.Video

	err := modlers.DB.Order("like_count desc").Find(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": video,
	})
	return
}
